#include "tools/my_tlv.h"
#include "crypt/crypt_7th.h"
#include "headers.h"
#include <string.h>

// 普通指令收发

int send_train(int netfd, const train_t *ptrain) {
	int ret;

	// 1. 发送 cmdstat
	ret = send(netfd, &ptrain->cmdstat, sizeof(cmdstat_t), MSG_NOSIGNAL);
	if(ret != sizeof(cmdstat_t)) {
		perror("send cmdstat");
		return -1;
	}

	// 2. 发送 length
	ret = send(netfd, &ptrain->length, sizeof(int), MSG_NOSIGNAL);
	if(ret != sizeof(int)) {
		perror("send length");
		return -1;
	}

	// 3. 发送 data
	int total = 0;
	while(total < ptrain->length) {
		ret = send(netfd, ptrain->data + total, ptrain->length - total, MSG_NOSIGNAL);
		if(ret <= 0) {
			perror("send data");
			return -1;
		}
		total += ret;
	}

	return 0;
}

int recv_train(int netfd, train_t *ptrain) {
	int ret;

	// 1. 接收 cmdstat
	ret = recv(netfd, &ptrain->cmdstat, sizeof(cmdstat_t), MSG_WAITALL);
	if(ret <= 0) {
		perror("recv cmdstat");
		return -1;
	}

	// 2. 接收 length
	ret = recv(netfd, &ptrain->length, sizeof(int), MSG_WAITALL);
	if(ret <= 0) {
		perror("recv length");
		return -1;
	}

	if(ptrain->length > sizeof(ptrain->data)) {
		fprintf(stderr, "数据长度过大: %d\n", ptrain->length);
		return -1;
	}

	// 3. 接收 data
	ret = recv(netfd, ptrain->data, ptrain->length, MSG_WAITALL);
	if(ret <= 0) {
		perror("recv data");
		return -1;
	}

	return 0;
}

int send_info(int fd, char mes[]) {
	train_t tra = {0};
	tra.cmdstat = RES;
	tra.length = strlen(mes);
	strcpy(tra.data, mes);
	return send_train(fd, &tra);
}

int checkToken(train_t *tdata_get) {
	if(tdata_get->length < sizeof(extra_data_t))
		return -1;
	extra_data_t *exdata = (extra_data_t *)tdata_get->data;
	char token[64] = {0};
	getToken(exdata->user, token);
	if(strcmp(token, exdata->token))
		return -1;
	return 0;
}
